package cn.icatw.leetcode.editor.cn;
//给你二叉树的根节点 root 和一个整数目标和 targetSum ，找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
//
// 叶子节点 是指没有子节点的节点。
//
//
//
//
//
//
//
// 示例 1：
//
//
//输入：root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
//输出：[[5,4,11,2],[5,8,4,5]]
//
//
// 示例 2：
//
//
//输入：root = [1,2,3], targetSum = 5
//输出：[]
//
//
// 示例 3：
//
//
//输入：root = [1,2], targetSum = 0
//输出：[]
//
//
//
//
// 提示：
//
//
// 树中节点总数在范围 [0, 5000] 内
// -1000 <= Node.val <= 1000
// -1000 <= targetSum <= 1000
//
//
// Related Topics 树 深度优先搜索 回溯 二叉树 👍 1118 👎 0


import java.util.ArrayList;
import java.util.List;

//Java：路径总和 II
public class T113_PathSumIi {
    public static void main(String[] args) {
        Solution solution = new T113_PathSumIi().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
            List<Integer> currentPath = new ArrayList<>();
            List<List<Integer>> result = new ArrayList<>();
            dfs(root, targetSum, currentPath, result);
            return result;
        }

        private void dfs(TreeNode node, int targetSum, List<Integer> currentPath, List<List<Integer>> result) {
            if (node == null) {
                return;
            }
            //    将当前节点加入路径
            currentPath.add(node.val);
            //    判断是否是叶子节点,是叶子节点则判断路径和是否等于目标值
            if (node.left == null && node.right == null && node.val == targetSum) {
                result.add(new ArrayList<>(currentPath));
            } else {
                //    不是叶子节点则继续递归
                dfs(node.left, targetSum - node.val, currentPath, result);
                dfs(node.right, targetSum - node.val, currentPath, result);
            }
            //    回溯，移除当前节点
            currentPath.remove(currentPath.size() - 1);
        }
    }

    //leetcode submit region end(Prohibit modification and deletion)
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
